package com.feng.util;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Map;
 
public class HttpClientUtils {
	private static int connectionTimeout = 8000;
	private static int soTimeout = 30000;
 
    /**
     * httpPost
     * @param url  路径
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url,JSONObject jsonParam){
        return httpPost(url, jsonParam, false);
    }
 
    /**
     * post请求
     * @param url         url地址
     * @param jsonParam     参数 放在RequestEntity
     * @param noNeedResponse    不需要返回结果
     * @return json
     */
    public static JSONObject httpPost(String url,JSONObject jsonParam, boolean noNeedResponse){
        //post请求返回结果
        DefaultHttpClient httpClient = new DefaultHttpClient();
        JSONObject jsonResult = null;
        HttpPost method = new HttpPost(url);
        try {
            if (null != jsonParam) {
                //解决中文乱码问题
                StringEntity entity = new StringEntity(jsonParam.toString(), "UTF-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            HttpResponse result = httpClient.execute(method);
            url = URLDecoder.decode(url, "UTF-8");
            /**请求发送成功，并得到响应**/
            if (result.getStatusLine().getStatusCode() == 200) {
                String str = "";
                try {
                    /**读取服务器返回过来的json字符串数据**/
                    str = EntityUtils.toString(result.getEntity(),"UTF-8");
                    if (noNeedResponse) {
                        return null;
                    }
                    /**把json字符串转换成json对象**/
                    jsonResult = JSONObject.fromObject(str);
                } catch (Exception e) {
                }
            }
        } catch (IOException e) {
        }finally{
			if(method != null){
				method.releaseConnection();
			}
		}
        return jsonResult;
    }
    /**
     * post请求
     * @param uri
     * @param params  参数拼接
     * @param httpContentCharset
     * @return
     * @throws Exception
     */
    public static String httpPost(String uri,Map<String,String> params,String httpContentCharset)throws Exception{
		PostMethod postMethod = null;
		try {
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(1000);
		    client.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);
		    
		    postMethod = new PostMethod(uri);
		    if(null != httpContentCharset){
		    	postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, httpContentCharset);
		    }
		    postMethod.addParameters(transFromMap(params));
    		client.executeMethod(postMethod);
    		String responsetext = postMethod.getResponseBodyAsString();
    		return responsetext;
		} catch (Exception e) {
			throw e;
		}finally{
			if(postMethod != null){
				postMethod.releaseConnection();
			}
		}
	}
    
    /***
	 * 请求信息放入RequestEntity
	 * @param uri 请求地址
	 * @param text 请求信息
	 * @return
	 * @throws Exception
	 */
	public static String postText(String uri,String text) throws Exception{
		PostMethod postMethod = null;
		try {
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
		    client.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);
		    
		    postMethod = new PostMethod(uri);
		    @SuppressWarnings("deprecation")
			StringRequestEntity entity = new StringRequestEntity(text);
		    postMethod.setRequestEntity(entity);
		    
    		client.executeMethod(postMethod);
    		String responsetext = postMethod.getResponseBodyAsString();
    		
    		return responsetext;
		} catch (Exception e) {
			throw e;
		}finally{
			if(postMethod != null){
				postMethod.releaseConnection();
			}
		}
	}
    
    /**
     * 发送get请求
     * @param url    路径
     * @return
     */
    public static JSONObject httpGet(String url){
        //get请求返回结果
        JSONObject jsonResult = null;
        try {
            DefaultHttpClient client = new DefaultHttpClient();
            //发送get请求
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
 
            /**请求发送成功，并得到响应**/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                /**读取服务器返回过来的json字符串数据**/
                String strResult = EntityUtils.toString(response.getEntity());
                /**把json字符串转换成json对象**/
                jsonResult = JSONObject.fromObject(strResult);
                url = URLDecoder.decode(url, "UTF-8");
            } else {
            	
            }
        } catch (IOException e) {
        }
        return jsonResult;
    }
    
    /**
	 * http GET 请求 但是参数不拼接到请求中 而是放到 queryString 中.
	 * @param uri
	 * @param paramMap
	 * @param httpContentCharset
	 * @return
	 * @throws Exception
	 */
	public static String httpGet(String uri,Map<String,String> paramMap,String httpContentCharset,int connectionTimeout) throws Exception{
		GetMethod getMethod = null;
		try {
			HttpClient client = new HttpClient();
			client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
		    client.getHttpConnectionManager().getParams().setSoTimeout(soTimeout);
		    
		    getMethod = new GetMethod(uri);
		    getMethod.setQueryString(transFromMap(paramMap));
		    if(null != httpContentCharset){
		    	client.getParams().setContentCharset(httpContentCharset);
		    	getMethod.getParams().setCredentialCharset(httpContentCharset);
		    	getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; text/html; charset="+httpContentCharset);
		    }
    		client.executeMethod(getMethod);
    		String responsetext = getMethod.getResponseBodyAsString();
    		return responsetext;
		} catch (Exception e) {
			throw e;
		}finally{
			if(getMethod != null){
				getMethod.releaseConnection();
			}
		}
	}
	
	/**
	 * 将Map<String,String>中的数据转换为httpclient  PostMehtod 需要的参数格式
	 * @param map
	 * @return
	 */
	private static NameValuePair[] transFromMap(Map<String,String> map){
		NameValuePair[] pairs = new NameValuePair[map.size()];
		int i = 0;
		for(String key :map.keySet()){
			pairs[i] = new NameValuePair();
			pairs[i].setName(key);
			pairs[i].setValue(map.get(key));
			i++;
		}
		return pairs;
	}
}
